<template>
  <div class="header">
    <!-- 折叠按钮 -->
    <div class="collapse-btn" @click="collapseChage">
      <i v-if="!collapse" class="el-icon-s-fold"></i>
      <i v-else class="el-icon-s-unfold"></i>
    </div>
    <div class="logo">
      <img :src="logoImg || '../src/assets/img/logo.png'" />{{ projectName }}
    </div>
    <div class="header-right">
      <div class="header-user-con">
        <div v-if="projectList.length >= 2">
          <el-select v-model="projectId" placeholder="请选择" @change="handleProject">
            <el-option v-for="item in projectList" :key="item.id" :label="item.projectName" :value="item.id">
            </el-option>
          </el-select>
        </div>
        <!-- 消息中心 -->
        <!-- <div class="btn-bell">
          <el-tooltip
            effect="dark"
            :content="message ? `有${message}条未读消息` : `消息中心`"
            placement="bottom"
          >
            <router-link to="/tabs">
              <i class="el-icon-bell"></i>
            </router-link>
          </el-tooltip>
          <span class="btn-bell-badge" v-if="message"></span>
        </div> -->
        <!-- 用户头像 -->
        <div class="user-avator">
          <img v-if="headImg" :src="headImg" />
          <img v-else src="../assets/img/img.jpg" />
        </div>
        <!-- 用户名下拉菜单 -->
        <el-dropdown class="user-name" trigger="click" @command="handleCommand">
          <span class="el-dropdown-link">
            {{ username }}
            <i class="el-icon-caret-bottom"></i>
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="user">个人中心</el-dropdown-item>
              <el-dropdown-item command="passwd">修改密码</el-dropdown-item>
              <el-dropdown-item divided command="loginout">退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>
  </div>
</template>
<script>
import { computed, onMounted, onBeforeMount, onBeforeUnmount } from "vue";
import { ref, reactive } from "vue";
import { useStore } from "vuex";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import SocketService from "../utils/websocket";
import parsing from "../assets/js/parsing";
import api from "../api/api";
let socket;
export default {
  setup() {
    const username = ref("");
    const message = 2;
    const projectList = ref([]);
    const projectId = ref();
    const projectName = ref("");
    const logoImg = ref("");
    const headImg = ref("");
    const isImgUrl = ref(true);
    const location_host = window.location.host;
    const timeInterval = ref(null);
    const store = useStore();
    if (localStorage.getItem("token")) {
      socket = reactive({
        socketServe: SocketService.Instance,
      });
      let promise1 = SocketService.Instance.connect();
      let promise2 = (socket.socketServe = SocketService.Instance);
      let promise3 = socket.socketServe.registerCallBack(
        "callback1",
        socket.socketServe
      );
      const timeSocketSend = ref(null);
      Promise.all([promise1, promise2, promise3]).then(function (values) {
        setTimeout(function () {
          socket.socketServe.send({
            optionCode: "serverAuth",
            time: parsing.getCurrentCompleteDate(),
            message: "Bearer " + localStorage.getItem("token"),
          });
        }, 500);
        timeInterval.value = setInterval(function () {
          socket.socketServe.send({
            optionCode: "serverAuth",
            time: parsing.getCurrentCompleteDate(),
            message: "Bearer " + localStorage.getItem("token"),
          });
        }, 600000);
      });
      timeSocketSend.value = setInterval(function () {
        socket.socketServe.send(1);
        // 如果连接失败或者没有连接  重新连接
        if (!socket.socketServe.connected) {
          socket.socketServe.connectRetryCount++;
          SocketService.Instance.connect();
          socket.socketServe.send({
            optionCode: "serverAuth",
            time: parsing.getCurrentCompleteDate(),
            message: "Bearer " + localStorage.getItem("token"),
          });
        }
      }, 30000);
    }
    // const sendData = () => {
    //   data.socketServe.send("发送数据");
    // };
    const getuserinfo = () => {
      api
        .postFormAPI("auth/user/info", {})
        .then((res) => {
          if (res.data.code == 1) {
            username.value =
              res.data.data.realName || res.data.data.roleNameList[0];
            localStorage.setItem("ms_username", res.data.data.realName);
            var userInfo = JSON.stringify(res.data.data);
            headImg.value = res.data.data.headImg;
            if (
              res.data.data.projectList &&
              res.data.data.projectList.length > 0
            ) {
              if (localStorage.getItem("projectId")) {
                for (var i = 0; i < res.data.data.projectList.length; i++) {
                  if (
                    res.data.data.projectList[i].id ==
                    localStorage.getItem("projectId")
                  ) {
                    projectId.value = res.data.data.projectList[i].id;
                    projectName.value =
                      res.data.data.projectList[i].projectName;
                    logoImg.value = res.data.data.projectList[i].logoImg;
                    localStorage.setItem(
                      "projectName",
                      res.data.data.projectList[i].projectName
                    );
                    localStorage.setItem(
                      "logoImg",
                      res.data.data.projectList[i].logoImg
                    );
                    localStorage.setItem(
                      "projectId",
                      res.data.data.projectList[i].id
                    );
                    localStorage.setItem(
                      "projectobj",
                      JSON.stringify(res.data.data.projectList[i])
                    );
                  }
                }
              } else {
                projectId.value = res.data.data.projectList[0].id;
                projectName.value = res.data.data.projectList[0].projectName;
                logoImg.value = res.data.data.projectList[0].logoImg;
                localStorage.setItem(
                  "projectName",
                  res.data.data.projectList[0].projectName
                );
                localStorage.setItem(
                  "logoImg",
                  res.data.data.projectList[0].logoImg
                );
                localStorage.setItem(
                  "projectId",
                  res.data.data.projectList[0].id
                );
                localStorage.setItem(
                  "projectobj",
                  JSON.stringify(res.data.data.projectList[0])
                );
              }
            }
            for (var i = 0; i < res.data.data.projectList.length; i++) {
              if (res.data.data.projectList[i].state == 0) {
                projectList.value.push(res.data.data.projectList[i]);
              }
            }
            localStorage.setItem("userInfo", userInfo);
          } else {
            if (res.status == 401) {
              setTimeout(function () {
                router.push("/login");
              }, 500);
              ElMessage.error("未授权，请重新登录");
            } else {
              ElMessage.error(res.data.message);
            }
          }
          //数据处理
        })
        .catch((err) => {
          console.log(err);
        });
    };
    const collapse = computed(() => store.state.collapse);
    // 侧边栏折叠
    const collapseChage = () => {
      store.commit("handleCollapse", !collapse.value);
    };
    onMounted(() => {
      getuserinfo();
      if (document.body.clientWidth < 1500) {
        collapseChage();
      }
    });

    // 用户名下拉菜单选择事件
    const router = useRouter();
    const handleCommand = (command) => {
      if (command == "loginout") {
        socket.socketServe.ws.close();
        window.clearInterval();
        localStorage.setItem("projectName", "");
        localStorage.setItem("projectId", null);
        localStorage.removeItem("token");
        localStorage.removeItem("projectId");
        localStorage.removeItem("userInfo");
        localStorage.removeItem("logoImg");
        localStorage.removeItem("projectobj");
        router.push("/login");
      } else if (command == "user") {
        router.push("/user");
      } else if (command == "passwd") {
        router.push("/passwd");
      }
    };
    // 切换项目
    const handleProject = (row) => {
      for (var i = 0; i < projectList.value.length; i++) {
        if (projectList.value[i].id == row) {
          projectId.value = projectList.value[i].id;
          projectName.value = projectList.value[i].projectName;
          logoImg.value = projectList.value[i].logoImg;
          localStorage.setItem("projectId", row);
          localStorage.setItem("projectName", projectList.value[i].projectName);
          localStorage.setItem("logoImg", projectList.value[i].logoImg);
          localStorage.setItem(
            "projectobj",
            JSON.stringify(projectList.value[i])
          );
        }
        if (i == projectList.value.length - 1) {
          router.go("0");
        }
      }
    };
    onBeforeUnmount(async () => {
      if (timeInterval.value) {
        clearInterval(timeInterval.value);
      }
    });
    return {
      username,
      message,
      location_host,
      collapse,
      // data,
      // sendData,
      collapseChage,
      handleCommand,
      handleProject,
      projectList,
      projectId,
      projectName,
      logoImg,
      headImg,
    };
  },
};
</script>
<style scoped>
.header {
  position: relative;
  box-sizing: border-box;
  width: 100%;
  height: 70px;
  /* font-size: 22px; */
  color: #fff;
}

.collapse-btn {
  float: left;
  padding: 0 21px;
  cursor: pointer;
  line-height: 70px;
}

.header .logo {
  display: flex;
  float: left;
  align-items: center;
  line-height: 70px;
}

.header .logo img {
  width: 4rem;
  /* border-radius: 50%; */
  margin-right: 10px;
}

.header-right {
  float: right;
  padding-right: 1rem;
}

.header-user-con {
  display: flex;
  height: 70px;
  align-items: center;
}

.btn-fullscreen {
  transform: rotate(45deg);
  margin-right: 5px;
  font-size: 24px;
}

.btn-bell,
.btn-fullscreen {
  position: relative;
  width: 30px;
  height: 30px;
  text-align: center;
  border-radius: 15px;
  cursor: pointer;
}

.btn-bell-badge {
  position: absolute;
  right: 0;
  top: -2px;
  width: 8px;
  height: 8px;
  border-radius: 4px;
  background: #f56c6c;
  color: #fff;
}

.btn-bell .el-icon-bell {
  color: #fff;
}

.user-name {
  margin-left: 10px;
}

.user-avator {
  margin-left: 20px;
  margin-right: 10px;
}

.user-avator img {
  display: block;
  width: 40px;
  height: 40px;
  border-radius: 50%;
}

.el-dropdown-link {
  color: #fff;
  cursor: pointer;
}

.el-dropdown-menu__item {
  text-align: center;
}
</style>
